/*******************************************************************************
 * Package: com.song.common.annotation.aop
 * Type:    CurrentLimiterA
 * Date:    2024-01-07 14:43
 *
 * Copyright (c) 2024 LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.common.annotation.aop;

import com.google.common.collect.Lists;
import com.song.common.annotation.CurrentLimiter;
import com.song.common.util.CommUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 功能描述：aop解析注解CurrentLimiter
 *
 * @author Songxianyang
 * @date 2024-01-07 14:43
 */
@Component
@Aspect
@Slf4j
public class CurrentLimiterAspect {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedisScript<Boolean> rateLimitLua;

    // 定义切面点
    @Pointcut("@annotation(com.song.common.annotation.CurrentLimiter)")
    public void current() {
        log.info("current");
    }

    @Before("current()")
    public void before(JoinPoint joinPoint) {
        // 1. 获得方法签名，作为 method Key
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        CurrentLimiter annotation = method.getAnnotation(CurrentLimiter.class);
        if (annotation == null) {
            return;
        }

        String key = annotation.methodKey();
        Integer limit = annotation.limit();

        // 如果没设置methodkey, 从调用方法签名生成自动一个key
        if (CommUtil.isEmpty(key)) {
            Class[] type = method.getParameterTypes();
            key = method.getClass() + method.getName();

            if (type != null) {
                String paramTypes = Arrays.stream(type)
                        .map(Class::getName)
                        .collect(Collectors.joining(","));
                log.info("param types: " + paramTypes);
                key += "#" + paramTypes;
            }
        }

        boolean acquired = stringRedisTemplate.execute(
                // Lua script的
                rateLimitLua,
                // Lua脚本中的Key列表
                Lists.newArrayList(key),
                // Lua脚本Value列表
                limit.toString()
        );

        if (!acquired) {
            log.error("您的访问被阻止, key={}", key);
            throw new RuntimeException("请勿重复访问！该接口被限流");
        }
    }
}
